package com.boot.study.user.service;

import com.boot.study.common.Result;
import com.boot.study.entity.User;
import com.boot.study.entity.UserExample;
import com.boot.study.exceptions.ServiceException;
import com.boot.study.mapper.UserMapper;
import com.boot.study.user.dto.RegisterUserRequest;
import com.boot.study.user.dto.RegisterUserResponse;
import com.boot.study.user.util.AssertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;


    public Result welcome() {
        Result<String> welcome = Result.success("欢迎进入crm系统");
        return welcome;
    }

    public Result registerUser(RegisterUserRequest userRequest) {
        List<User> users = userMapper.queryByUserName(userRequest.getUserName());
        AssertUtil.assertIsTrue(users.size() > 0, "用户已经存在");
        User user = new User();
        BeanUtils.copyProperties(userRequest, user);
        int insert = userMapper.insert(user);
        AssertUtil.assertIsTrue(users.size() <= 0, "注册用户失败");
        RegisterUserResponse response = buildRegisterResult(user);
        Result result = Result.success(response);
        return result;
    }

    private RegisterUserResponse buildRegisterResult(User user) {
        RegisterUserResponse response = new RegisterUserResponse();
        response.setId(user.getId());
        response.setUserName(user.getUserName());
        return response;
    }
}
